package com.qiaofang.collectmanage.dao.impl;
/**
 * @Author:   yi.li
 */
import com.qiaofang.collectmanage.dao.CollectRuleDao;
import com.qiaofang.collectmanage.dao.ElementRuleDao;
import com.qiaofang.collectmanage.dao.domain.CollectRule;
import com.qiaofang.collectmanage.dao.domain.ElementRule;
import com.qiaofang.collectmanage.dao.mapper.CollectRuleMapper;
import com.qiaofang.collectmanage.dao.mapper.ElementRuleMapper;
import com.qiaofang.collectmanage.dao.targetmapper.TargetCollectRuleMapper;
import com.qiaofang.collectmanage.dao.targetmapper.TargetElementRuleMapper;
import com.qiaofang.collectmanage.dao.util.CollectRuleDaoConvert;
import com.qiaofang.collectmanage.dao.util.ElementRuleDaoConvert;
import com.qiaofang.collectmanage.stub.bean.CrawlerCollectRuleDTO;
import com.qiaofang.collectmanage.stub.bean.CrawlerElementRuleDTO;
import com.qiaofang.collectmanage.stub.bean.SearchCollectRulePostDTO;
import com.qiaofang.collectmanage.stub.constants.DeletedEnum;
import com.qiaofang.common.datasource.tkmapper.InsertListSelectiveMapperUtil;
import com.qiaofang.common.exception.BusinessException;
import com.qiaofang.common.model.page.PageDTO;
import com.qiaofang.common.page.PageUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Repository("collectRuleDao")
public class CollectRuleDaoImpl implements CollectRuleDao {

    @Autowired
    CollectRuleMapper collectRuleMapper;

    @Autowired
    ElementRuleMapper elementRuleMapper;



    /**
     * 目标数据源操作集
     * 规则
     */
    @Autowired
    TargetElementRuleMapper targetElementRuleMapper;

    /**
     * 目标数据源操作集
     * 元素规则操作elementRule
     */
    @Autowired
    TargetCollectRuleMapper targetCollectRuleMapper;

    @Autowired
    private ElementRuleDao elementRuleDao;
    @Override
    public CollectRule getCollectRuleById(Integer id) {
        CollectRule collectRule = new CollectRule();
        collectRule.setId(id);
        return collectRuleMapper.selectOne(collectRule);
    }

    @Override
    public CollectRule getCollectRuleByUuid(String uuid) {
        CollectRule collectRule = new CollectRule();
        collectRule.setUuid(uuid);
        List<CollectRule> list = collectRuleMapper.select(collectRule);
        if(list!=null&&!list.isEmpty()){
            return list.get(0);
        }
        return null;
    }

    @Override
    public int updateCollectRule(CollectRule collectRule) {
        Example ex = new Example(CollectRule.class);
        ex.createCriteria()
                .andIsNotNull("id")
                .andEqualTo("id", collectRule.getId());
        return collectRuleMapper.updateByExampleSelective(collectRule, ex);
    }

    @Override
    public int removeCollectRule(Integer id) {
        Example ex = new Example(CollectRule.class);
        ex.createCriteria().andEqualTo("id", id);
        CollectRule collectRule = new CollectRule();
        collectRule.setDeleted(DeletedEnum.YES.getValue());
        collectRule.setUpdatedTime(new Date());
        return collectRuleMapper.updateByExampleSelective(collectRule, ex);
    }

    @Override
    public List<CollectRule> listCollectRule(CollectRule collectRule) {
        if (collectRule == null) {
            collectRule = new CollectRule();
        }
        return collectRuleMapper.select(collectRule);
    }
    @Override
    public List<CollectRule> getListByCollectRule(CollectRule collectRule) {
        if (collectRule == null) {
            collectRule = new CollectRule();
        }
        return collectRuleMapper.select(collectRule);
    }

    @Override
    public void saveCollectRule(CollectRule collectRule) {
        int i = collectRuleMapper.insertSelective(collectRule);
        if (i == 0) {
            throw new BusinessException("新增采集规则失败");
        }
    }

    @Override
    public CollectRule getCollectRule(CollectRule collecRule) {
        return collectRuleMapper.selectOne(collecRule);
    }


    @Override
    public List<CollectRule> searchCollectRulePage(SearchCollectRulePostDTO dto, PageDTO page) {
        Example example = new Example(CollectRule.class);
        page.setSortBy("created_time");
        page.setDesc("desc");
        String orderBy = page.getSortBy()+" "+ page.getDesc();
        example.setOrderByClause(orderBy);

        example.createCriteria()
                .andEqualTo("city", dto.getCity())
                .andEqualTo("source", dto.getSource())
                .andEqualTo("belonger", dto.getBelonger())
                .andEqualTo("collectHouseType", dto.getCollectHouseType())
                .andEqualTo("collectType", dto.getCollectType())
                .andEqualTo("deleted",DeletedEnum.NO.getValue());

        return collectRuleMapper.selectByExampleAndRowBounds(example, PageUtil.getRowBounds(page));
    }

    @Override
    public Long countSearchCollectRulePage(SearchCollectRulePostDTO dto) {
        Example example = new Example(CollectRule.class);
        example.createCriteria()
                .andEqualTo("city", dto.getCity())
                .andEqualTo("source", dto.getSource())
                .andEqualTo("belonger", dto.getBelonger())
                .andEqualTo("collectHouseType", dto.getCollectHouseType())
                .andEqualTo("collectType", dto.getCollectType())
                .andEqualTo("deleted",DeletedEnum.NO.getValue());

        return Long.valueOf(collectRuleMapper.selectCountByExample(example));
    }

    @Override
    public int saveCollectRuleBatch(List<CollectRule> collectRuleList) {
        return InsertListSelectiveMapperUtil.insertListSelective(collectRuleMapper, collectRuleList);
    }

    @Override
    public com.qiaofang.collectmanage.domain.CollectRule findById(CollectRule collectRule) {
        CollectRule rule   = getCollectRule(collectRule);
        com.qiaofang.collectmanage.domain.CollectRule domainRule = CollectRuleDaoConvert.convertCollectRuleToResolveCollect(rule);
        String uuid = rule.getUuid();
        List<Integer> list = elementRuleDao.findDepthsByUuid(uuid);
        List<List<ElementRule>> listElements = new ArrayList<>();
        List<List<com.qiaofang.collectmanage.domain.ElementRule>> domainListElements = new ArrayList<>();
        for (Integer depth : list) {
            listElements.add(elementRuleDao.findByUuidAndDepth(uuid, depth));
            List<ElementRule> elementRules = elementRuleDao.findByUuidAndDepth(uuid, depth);
            domainListElements.add(elementRules.stream().map(ElementRuleDaoConvert::convertElementRuleToResolveElement).collect(Collectors.toList()));
        }
        domainRule.setListElements(domainListElements);
        return domainRule;
    }

    @Override
    public CrawlerCollectRuleDTO findCrawlerCollectRuleById(CollectRule collectRule) {
        CollectRule rule   = getCollectRule(collectRule);
        CrawlerCollectRuleDTO  domainRule = CollectRuleDaoConvert.convertCollectRuleToCrawlerCollectRule(rule);
        String uuid = rule.getUuid();
        List<Integer> list = elementRuleDao.findDepthsByUuid(uuid);
        List<List<CrawlerElementRuleDTO>> domainListElements = new ArrayList<>();
        for (Integer depth : list) {
            List<ElementRule> elementRules = elementRuleDao.findByUuidAndDepth(uuid, depth);
            if(!elementRules.isEmpty()) {
                domainListElements.add(elementRules.stream().map(ElementRuleDaoConvert::convertElementRuleToCrawlerElementRuleDTO).collect(Collectors.toList()));
            }
        }
        domainRule.setListElements(domainListElements);
        return domainRule;
    }


    @Override
    public List<String> getCitys() {
        return collectRuleMapper.getCitys(DeletedEnum.NO.getValue());
    }

    @Override
    public List<String> getSources() {
        return collectRuleMapper.getSources(DeletedEnum.NO.getValue());
    }

    /**
     * 从源库导数据到目标库
     * @desc 上线频道数据
     * @param uuid
     */
    @Override
    public void inputCityDataToDbByUuid(List<String> uuids) {

        List<CollectRule> allCollectRule = new ArrayList<>();
        List<ElementRule> allElementRules = new ArrayList<>();
        if(uuids!=null){
            uuids.forEach(uuid->{
                CollectRule collectRule = new CollectRule();
                collectRule.setUuid(uuid);
                List<CollectRule> collectRules = collectRuleMapper.select(collectRule);

                if(collectRules!=null&&!collectRules.isEmpty()){
                    allCollectRule.add(collectRules.get(0));
                    ElementRule elementRule = new ElementRule();
                    elementRule.setCollectRuleUuid(uuid);
                    elementRule.setDeleted(DeletedEnum.NO.getValue());
                    List<ElementRule> elementRules = elementRuleMapper.select(elementRule);
                    for (ElementRule elementRule1:elementRules){
                        allElementRules.add(elementRule1);
                    }
                }
            });
            allElementRules.forEach(item->item.setId(null));
            allCollectRule.forEach(item->item.setId(null));

            targetCollectRuleMapper.insertList(allCollectRule);
            targetElementRuleMapper.insertList(allElementRules);
        }
    }
    @Override
    public List<CollectRule> findAllBySourceAndCollectType(String source,String collectType) {
        CollectRule collectRule = new CollectRule();
        collectRule.setSource(source);
        collectRule.setCollectType(collectType);
        List<CollectRule> list = collectRuleMapper.select(collectRule);
        return list;
    }


    @Override
    public List<CollectRule> listCollectRuleByUuids(List<String> uuidList) {
        Example ex = new Example(CollectRule.class);
        ex.createCriteria().andIn("uuid",uuidList);
        return collectRuleMapper.selectByExample(ex);
    }

}
